package com.cqust.icc.sqlite.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;

/*
 * 数据库操作类
 * */
public class MyDbService {

    private final MyDbHelper myDbHelper;

    public MyDbService(Context context) {
        myDbHelper = new MyDbHelper(context);
    }

    public void insertPerson(ContentValues value) {
        SQLiteDatabase writableDatabase = getDb();
        writableDatabase.insertOrThrow("User", null, value);
    }

    @SuppressLint("Range")
    public String login(String name) {
        SQLiteDatabase writableDatabase = getDb();

        String res = null;
        Cursor cursor = writableDatabase.rawQuery("select * from User where username = ? ", new String[]{name}, null);
        if (cursor.moveToFirst()) {
            res = cursor.getString(cursor.getColumnIndex("password"));
        }
        cursor.close();
        return res;
    }

    public SQLiteDatabase getDb() {
        return myDbHelper.getWritableDatabase();
    }

    @SuppressLint("Range")
    public ArrayList<User> getPersonList() {
        SQLiteDatabase writableDatabase = getDb();
        ArrayList<User> list = new ArrayList<>();
        Cursor cursor = writableDatabase.rawQuery("select * from User", null);

        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                String name = cursor.getString(cursor.getColumnIndex("username"));
                String password = cursor.getString(cursor.getColumnIndex("password"));
                String _id = cursor.getString(cursor.getColumnIndex("_id"));
                int age = cursor.getInt(cursor.getColumnIndex("age"));
                user.setName(name);
                user.setPassword(password);
                user.setId(_id);
                user.setAge(age);
                list.add(user);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return list;
    }

    public void delete(String username) {
        SQLiteDatabase writableDatabase = getDb();
        writableDatabase.delete("User", "username = ?", new String[]{username});
    }

    public int update(ContentValues values) {
        SQLiteDatabase writableDatabase = getDb();
        return writableDatabase.update("User", values, " username = ?", new String[]{String.valueOf(values.get("username"))});
    }
}
